import React, {Component} from "react";
import moment from "moment";
import {
  Form,
  Input,
  Select,
  Button,
  Radio,
  Checkbox,
  DatePicker,
  InputNumber,
  Tag
} from "antd";
import {
  getDictInformation,
  publicCommonDictGetDictByCodeTypes, //数字字典
  taskGetStepOneDetail,
  taskGetServerTypeList,
  taskGetIndustriesList
} from "../../../services/api";
import Menu from "./Menu";
import "../Task.less";
import PCascader from "../../../components/Pro/PCascader";

const FormItem = Form.Item;
const {Option} = Select;
const {TextArea} = Input;
const {RangePicker} = DatePicker;
const dateFormat = "YYYY-MM-DD";
const Search = Input.Search;
@Form.create()
export default class TaskDetailBasicInfomation extends Component {

  state = {
    comTaskId: this.props.comTaskId,
    taskType: "",
    taskNature: "",
    taskNatures: "",
    urgentLevels: "",
    urgentLevel: "",
    taskLevel: "",
    serviceType: "",
    perNum: "",
    startDate: "",
    endDate: "",
    taskContent: "",
    taskAddress: "",
    execRange: "",
    disabled: true,
    selectedTags: [],
    serviceTypes: [],
    taskLevels: [],
    taskTypes: [],
    addressLatitude: "",
    addressLongitude: "",
    showInitialMarker: true,
    allAddress: [],//省市区
    place: ""
  };
  componentWillMount = () => {
    //地图script
    this.loadMapScript();
    this.taskGetTaskById();
  }

  componentDidMount() {
    //加载当前页面除了基础信息之外的所有异步请求
    this.allAjax();

  }

  allAjax = () => {
    Promise
      .all([
        taskGetServerTypeList(),
        taskGetIndustriesList(),
        publicCommonDictGetDictByCodeTypes({
          codeTypes: "taskType,serviceTypeList,taskNature,urgentLevel,taskLevel"
        })
      ])
      .then(([data1, data2, data3,]) => {
        this.getTaskGetServerTypeList(data1);
        this.getTaskGetIndustriesList(data2);
        this.getPublicCommonDictGetDictByCodeTypes(data3);
      })
      .catch((err1, err2, err3) => {
        console.log(err1, "获取服务类型-err");
        console.log(err2, "获取任务类型-err");
        console.log(err3, "publicCommonDictGetDictByCodeTypes-err");
      });
  }

  //获取服务类型
  getTaskGetServerTypeList = (data) => {
    this.setState({serviceTypes: data.data});
    console.log(data, "获取服务类型");
  }
  //获取任务类型
  getTaskGetIndustriesList = (data) => {
    this.setState({taskTypes: data.data});
    console.log(data, "获取任务类型");
  }
  /* 字典 */
  getPublicCommonDictGetDictByCodeTypes = (data) => {
    //数字字典
    console.log(data, "publicCommonDictGetDictByCodeTypes-data");
    const dict = data.data;
    this.setState({
      taskNatures: dict.taskNature || [], //任务性质
      urgentLevels: dict.urgentLevel || [], //紧急程度
      taskLevels: dict.taskLevel || [] //任务等级
    });
  };


  /* 基础信息 */
  taskGetTaskById = () => {
    const {basicInfo} = this.props;

    const {taskType, taskNature, urgentLevel, taskLevel, serviceType, perNum, startDate, endDate, taskContent, taskAddress, execRange, addressLongitude, addressLatitude, allAddress} = basicInfo;
    this.setState({
      taskType,
      taskNature,
      urgentLevel,
      taskLevel,
      serviceType: serviceType.split(','),
      perNum,
      startDate,
      endDate,
      taskContent,
      taskAddress,
      execRange,
      addressLongitude,
      addressLatitude,
      allAddress
    });

  };


  loadMapScript = () => {
    const script = document.createElement("script");
    script.src =
      "http://webapi.amap.com/maps?v=1.4.4&key=9066916e054aa3083a6f081a2a9f9d7a";
    document.body.appendChild(script);

    const script2 = document.createElement("script");
    script2.src =
      "http://cache.amap.com/lbs/static/addToolbar.js";
    document.body.appendChild(script2);
    this.loading();

  };
  loading = () => {
    let _this = this;

    function nextStep() {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve("AMap" in window);
        }, 500);
      });
    }

    async function ajaxMap() {
      let ifComplete = false;
      for (var i = 0; i < 10; i++) {
        if (!ifComplete) {
          ifComplete = await nextStep();
        } else {
          if (ifComplete) {
            console.log("地图初始化中。。。");
            (_this.state.addressLongitude!='' && _this.state.addressLatitude!='') &&
            _this.initialMap(_this.state.addressLongitude, _this.state.addressLatitude);
          } else {
            message.error("网络超时")
          }
        }
      }
    }

    ajaxMap();
  }
  initialMap = (lng = '116.397428', lat = '39.90923') => {
    const that = this;
    const {AMap} = window;
    var map = new AMap.Map('mapContainer', {
      resizeEnable: true,
      zoom: 14,
      center: [lng, lat],
      // zoomEnable:false,//是否可缩放
      // dragEnable: false,  //是否可拖拽
    });
    this.setState({map});
    //是否显示初始化的标注
    let showInitialMarker = this.state.showInitialMarker;
    if (showInitialMarker) {
      let marker = new AMap.Marker({
        icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_r.png",
        position: [lng, lat]
      });
      marker.setMap(map);
    }

  }


  render() {
    const {submitting} = this.props;
    const {getFieldDecorator} = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10}
      }
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 10, offset: 7}
      }
    };

    const {serviceTypes, taskLevels, taskTypes, startDate, endDate, taskAddress, allAddress, taskNatures, urgentLevels} = this.state;
    return (
      <div className="TaskDetail">
        <Form style={{marginTop: 24}}>
          <FormItem {...formItemLayout} label="任务所属类型">
            {getFieldDecorator("taskType", {
              initialValue: this.state.taskType,
              rules: [{required: true, message: "请选择"}]
            })(
              <Select disabled={this.state.disabled} placeholder="请选择">
                {taskTypes && taskTypes.map((val, index) => {
                  return (
                    <Option key={index} value={val.codeValue}>
                      {val.label}
                    </Option>
                  );
                })}
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="任务性质">
            {getFieldDecorator("taskNature", {
              initialValue: this.state.taskNature,
              rules: [
                {
                  required: true,
                  message: "请选择"
                }
              ]
            })(
              <Radio.Group disabled={this.state.disabled}>
                {taskNatures && taskNatures.map(val => {
                  return (
                    <Radio key={val.configDictId} value={val.codeValue}>
                      {val.label}
                    </Radio>
                  );
                })}
              </Radio.Group>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="紧急程度">
            {getFieldDecorator("urgentLevel", {
              initialValue: this.state.urgentLevel,
              rules: [
                {
                  required: true,
                  message: "请选择"
                }
              ]
            })(
              <Radio.Group disabled={this.state.disabled}>
                {urgentLevels && urgentLevels.map(val => {
                  return (
                    <Radio key={val.configDictId} value={val.codeValue}>
                      {val.label}
                    </Radio>
                  );
                })}
              </Radio.Group>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="任务等级">
            {getFieldDecorator("taskLevel", {
              initialValue: this.state.taskLevel,
              rules: [{required: true, message: "请选择"}]
            })(
              <Select disabled={this.state.disabled} placeholder="请选择">
                {taskLevels && taskLevels.map((val, index) => {
                  return (
                    <Option key={index} value={val.codeValue}>
                      {val.label}
                    </Option>
                  );
                })}
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="服务类型">
            {getFieldDecorator("serviceType", {
              initialValue: this.state.serviceType,
              rules: [
                {
                  required: true,
                  message: "请选择"
                }
              ]
            })(
              <Checkbox.Group disabled={this.state.disabled}>
                {serviceTypes.map((val, index) => {
                  return (
                    <Checkbox key={index} value={val.codeValue}>
                      {val.label}
                    </Checkbox>
                  );
                })}
              </Checkbox.Group>
            )}
          </FormItem>

          <FormItem {...formItemLayout} label="任务所需人数">
            {getFieldDecorator("perNum", {
              initialValue: this.state.perNum,
              rules: [
                {
                  required: true,
                  message: "请输入"
                },
              ]
            })(
              <InputNumber
                disabled={this.state.disabled}
                autosize={{minRows: 2, maxRows: 6}}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="起止时间">
            {getFieldDecorator("taskDate", {
              initialValue: [
                moment(startDate, dateFormat),
                moment(endDate, dateFormat)
              ],
              rules: [{required: true, message: "请选择生效日期"}]
            })(
              <RangePicker
                disabled={this.state.disabled}
                placeholder={["开始日期", "结束日期"]}
                style={{width: "100%"}}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="任务内容">
            {getFieldDecorator("taskContent", {
              initialValue: this.state.taskContent,
              rules: [
                {
                  required: true,
                  message: "请输入"
                },
              ]
            })(
              <TextArea
                disabled={this.state.disabled}
                autosize={{minRows: 2, maxRows: 6}}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label="任务城市">
            {getFieldDecorator("allAddress", {
              initialValue: this.state.allAddress,
              rules: [
                {
                  required: true,
                },
              ]
            })(<PCascader disabled={this.state.disabled} placeholder="请选择" onChange={this.changeProvinceValue}/>)}
          </FormItem>
          <FormItem {...formItemLayout} label="具体地址">
            {getFieldDecorator("taskAddress", {
              initialValue: this.state.taskAddress,
              rules: [
                {
                  required: true,
                },
                {
                  max: 100,
                  message: "请输入少于100个汉字"
                },
              ]
            })(<Search disabled={this.state.disabled} placeholder="请输入" onSearch={this.handleKeyUp}
                       enterButton={false}/>)}
          </FormItem>
          <FormItem {...submitFormLayout} label="">
            <div style={{width: '100%', height: 230, overflow: 'hidden'}}>
              <div id="mapContainer" style={{width: '100%', height: 250}}></div>
            </div>
          </FormItem>
          <FormItem {...formItemLayout} label="执行范围">
            {getFieldDecorator("execRang" +
              "" +
              "5257" +
              "e", {
              initialValue: this.state.execRange,
              rules: [{required: true, message: "请输入"}]
            })(<Input disabled={this.state.disabled} addonAfter="米"/>)}
          </FormItem>
        </Form>
      </div>
    );
  }
}
